<template>
  <div class='order_mana_box'>
    <tab :tabs="tablist" :activeName="activeName" @tabClick="handleTabClick"></tab>
    <div class='date_box'>
      <span class="color-gray6B">时间:</span>
      <el-date-picker v-model="daterange" type='datetimerange' range-separator='-' 
      start-placeholder='开始日期' end-placeholder='结束日期' :picker-options="pickerOptions" @change="chooseDate"></el-date-picker>
      <!-- <el-checkbox v-model="hasInvoice" class="query-falg">申请发票</el-checkbox> -->
      <span class="color-gray6B">商品名称</span>
      <div class="input_style">
        <el-input v-model="searchName" placeholder="请输入内容商品名称"></el-input>
      </div>
      
      <el-button type='primary' class="btn-query" @click="fetchOrderMana">&nbsp;&nbsp;查询&nbsp;&nbsp;</el-button>
    </div>
     <div class="order_mana_wrapper">
      <div v-if="isEmptyArray(filterOrderList)" class="no-content">
        暂时没有数据
      </div>
      <!-- 待支付和待发货分开装 -->
      <div class='payinfo_box' v-for='(orderItem, orderIndex) in filterOrderList' :key='orderIndex' >
        <div class='payinfo_head' style="overflow: hidden">
          <div class="fl">
            <p class='status'> {{orderItem | webOrderFilter}}</p>
            <p class='detail'>
              {{orderItem.createTime}}&nbsp;&nbsp;|&nbsp;&nbsp;{{orderItem.recName}}&nbsp;&nbsp;<span v-show="orderItem.payType !== -1">|&nbsp;&nbsp;{{payType[orderItem.payType]}}</span>
            </p>
          </div>
          <div class='fr detail'>
            <p >订单总金额 : <em class='money'>{{orderItem.finalAmount | floatPrices}}</em>元</p>
            <span v-if="(orderItem.payStatus === 0 || orderItem.payStatus === 3)&& orderItem.acceptanceAmount > 0">待支付金额 : <em class='money'>{{orderItem.finalAmount - orderItem.acceptanceAmount | floatPrices}}</em>元</span>
          </div>
        </div>
        <div class='payinfo_content'>
          <div class='pay_img'>
            <img class="img" :src="prefixImg + orderItem.img" @error="catchErrorImage"/>
          </div>
          <div class='order_info'>
            <p class='order_num'>订单编号:{{orderItem.orderId}}</p>
            <p>共 {{orderItem.productNumber}} 类产品</p>
          </div>
          <div class='fr order_rt'>
            <!-- <p class='time_down' v-if="orderItem.orderStatus === 0 && orderItem.payStatus  === 0 && orderItem.payMode === 0" v-show="orderItem.leftTime">剩余:{{orderItem.leftTime}}</p> -->
            <span class="btn el-button--danger btn-ora" 
              @click.stop="immediatePay(orderItem)"
              v-if="orderItem.orderStatus === 0 && (orderItem.payStatus === 0 || orderItem.payStatus === 3) && (orderItem.payMode === 0 || orderItem.payMode === -1)">立即支付</span>

            <span class="btn el-button--danger" 
              v-if="orderItem.orderStatus === 0 && (orderItem.payStatus === 0 || orderItem.payStatus === 3) && orderItem.payMode === 1"
              @click.stop="uploadPayment(orderItem.orderId)">上传支付凭证</span>

            <span class="btn btn-yellow" 
              v-if="orderItem.orderStatus === 0 && (orderItem.payStatus === 0 || orderItem.payStatus === 3) && orderItem.payMode === 1 && !(orderItem.hasInvoice === true && orderItem.finalAmount > 10000)" 
              style="margin-top:10px; margin-left: 0;"
              @click.stop="immediatePay(orderItem)">更换支付方式</span>
            
            <p class='color-blue btn-order' v-if="orderItem.payStatus === 2">支付审核中</p>
            <p>
              <router-link tag="a" :to="{name: 'orderDetail', params: { 'orderId': orderItem.orderId }}" class='btn-order color-blue'>订单详情</router-link>
              <span
               class='btn-order color-blue'
               v-if="orderItem.enableCancel"
               @click.stop="showCancelOrder(orderItem.orderId)">取消订单</span>
            </p>
            <!-- 查看物流 @mouseenter="fetchWatchTransport(orderItem.orderId), currentTransActive = orderIndex"-->
            <div v-if="orderItem.deliverStatus === 2 && !orderItem.urgent" class='btn-order color-blue transport_tip' >
              <div
                @mouseenter="fetchWatchTransport(orderItem.orderId), currentTransActive = orderIndex"
                @mouseleave="transVisi = false, currentTransActive = -1"
                @click="orderDetailLink(orderItem.orderId)">
                <span>查看物流</span>
              <div class="transport_tip_inner"
                @mouseenter="transVisi = true, currentTransActive = orderIndex"
                @mouseleave="transVisi = false ,currentTransActive = -1"
                v-show="transVisi && currentTransActive === orderIndex">
                <div class="transport_tip_box">
                  
                  <p class="trans_company">{{transObj.shipperName}}- {{transObj.logisticCode}}</p>
                  <p v-if="transObj.shipperCode === 'SF'">
                    顺丰快递暂不提供物流查询,
                    <a class="color-blue" @click.stop href="http://www.kuaidi100.com" target="_blank">快递查询</a>
                  </p>
                  <p v-else-if="!transSuccess">
                   暂无快递轨迹
                    <a class="color-blue" @click.stop href="http://www.kuaidi100.com" target="_blank">快递查询</a>
                  </p>
                  <ul class="transport_tip_group" v-else>
                    <li class="transport_tip_item " :class="{'transport_tip_item_active': index === 0}" v-for="(item, index) in translist" :key="index">
                      <p>{{item.acceptStation}} <span v-if="item.Remark">[{{item.remark}}]</span></p>
                      <p>{{item.acceptTime}}</p>
                    </li>
                  </ul>
                </div>
              </div>
              </div>
            </div>
            <p class='color-blue btn-order'v-if="orderItem.hasInvoice">已申请发票</p>
            <p class='color-blue btn-order'v-if="hasAnother(orderItem.orderStatus, orderItem.deliverStatus)" @click="fetchAnotherOrder(orderItem.orderId)">再次购买</p>
          </div>
        </div>
      </div>
      <!-- 分页 -->
      <el-row v-if="orderManaObj.page && orderManaObj.page.totalPages > 1">
        <el-pagination class="page_box"  layout="total, prev, pager, next, ->" :current-page.sync="page" 
          :total="orderManaObj.page.totalRecords" :page-size="orderManaObj.page.pageSize" @current-change="handlePage" ></el-pagination>
      </el-row>
     </div>
    <!-- 上传支付凭证 -->
    <el-dialog title="上传支付凭证" :visible.sync="payVoucherVisi" width="622px" top="20vh" center>
      <voucher :orderId="paymentId" @close="closeVoucherDialog"></voucher>
    </el-dialog>
    <!-- 取消订单的弹窗 cancelVisi -->
    <el-dialog  title="取消订单原因" :visible.sync="cancelVisi" width="450px" center :before-close="cancelReasonPop" top="20vh">
      <textarea v-model="cancelReason" class="cancelarea" maxlength="100" placeholder="请输入取消订单的原因" rows="8"></textarea>

      <span class="word_num">{{cancelTxtLen}}/<em>100</em></span>
      <div style="overflow: hidden;">
          <el-button type="primary"  class="submitBtn" @click="submitCancelOrder" :disabled="cancelTxtLen === 0 " >提交原因</el-button>
      </div>
    </el-dialog>
    <!-- 再来一单 -->
    <el-dialog title="提示" :visible.sync="showGetMoreMsgVisi" width="450px" >
      <div class="">
       <p class="mar-bt18 ft-16" v-for="(item, index) in getMoreMsg" :key="index">{{item}}</p>
      </div>
      <div class="txt-center" slot="footer">
        <el-button type="primary" @click="handleMoreBtn">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import {FormItem, Button, Upload, Input, DatePicker, Tabs, TabPane, Select, Option, Dialog, Form, Pagination, Row, Checkbox, Tooltip} from 'element-ui'
  import {getOrderMana, cancelOrder, getTracesInfo, getAnotherOrder} from '@/service/get-data'
  import {formatDate} from '@/tool/tool'
  import {payType, prefixImg} from '@/tool/index'
  import {voucher, tab} from '@/components/index'
  import {getCookie, setSession} from '@/config/mUntils'
  import {mapActions, mapState} from 'vuex'

  export default{
    components: {
      elFormItem: FormItem,
      elButton: Button,
      elUpload: Upload,
      elInput: Input,
      elDatePicker: DatePicker,
      elTabs: Tabs,
      elTabPane: TabPane,
      elSelect: Select,
      elOption: Option,
      elDialog: Dialog,
      elForm: Form,
      elPagination: Pagination,
      elRow: Row,
      elCheckbox: Checkbox,
      elTooltip: Tooltip,
      voucher,
      tab
    },
    data () {
      return {
        loadImg: require('../../../images/newload.png'),
        tablist: [
          {name: 'all', text: '全部订单'},
          {name: '0', text: '待支付'},
          {name: '1', text: '待发货'},
          {name: '2', text: '已发货'},
          {name: '3', text: '已结束'},
          {name: '4', text: '已取消'}],
        webOrderStatus: -1,
        paymentId: '', // 当前订单的id
        payVoucherVisi: false,
        dialogVisible: false,
        dialogImageUrl: '',
        orderStatus: -1, // 订单状态
        payStatus: -1,  // 支付状态
        deliverStatus: -1, // 发货状态
        startTime: '', // 开始时间
        endTime: '', // 结束时间
        hasInvoice: '', // 查询 发票条件
        page: 1, // 当前页数
        number: '10', // 每页显示数
        orderManaObj: {}, // 订单管理列表
        activeName: this.$route.query.name || 'all',
        pickerOptions: {
          shortcuts: [{
            text: '最近三个月',
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近半年',
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 183)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近一年',
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 365)
              picker.$emit('pick', [start, end])
            }
          }]
        },
        timer: '',
        cancelVisi: false, // 显示取消订单留言的弹窗
        cancelReason: '', // 取消订单的原因
        daterange: '', // 查询条件 时间绑定值
        searchName: '', // 查询条件 商品名称
        cancelOrderId: '', // 取消订单的ID
        transVisi: false,
        currentTransActive: -1, // 游标
        noTransInfo: '', // 没有物流信息
        transState: 2, // 物流状态
        transSuccess: false,
        translist: [
        ],
        transObj: {
        },
        getMoreProductIds: [], // 再来一单成功的规格ID数组
        showGetMoreMsgVisi: false, // 再来一单的弹窗
        getMoreMsg: [], // 再来一单信息展示
        exception: false // 异常与取消的单子
        // acceptAmountVisi: false
      }
    },
    computed: {
      ...mapState({
        acceptanceAmount: state => state.user.acceptanceAmount,
        levelInfoObj: state => state.levelInfoObj
      }),
      payType () {
        return payType
      },
      cancelTxtLen () {
        return this.cancelReason.length
      },
      prefixImg () {
        return prefixImg
      },
      // 订单列表 待发货和待支付的单子不要混合
      filterOrderList () {
        let list = []
        if (this.orderManaObj.list && this.orderManaObj.list.length > 0) {
          list = this.orderManaObj.list.filter((item, index) => {
            return (item.payStatus !== 0 && this.activeName === '1') || (this.activeName !== '1')
            // v-if="(orderManaObj.list.length >0 && activeName === '1' && orderItem.payStatus !== 0) || (orderManaObj.list.length >0 && activeName !== '1')"
          })
        }
        return list
      },
      Exam () {
        return getCookie('Exam') - 0
      }
    },
    methods: {
      ...mapActions(['getUserLevelInfo']),
      isEmptyArray (arr) {
        return Array.isArray(arr) && !arr.length
      },
      catchErrorImage (e) {
        e.target.src = require('img/newload.png')
      },
      // 计算剩余时间 倒计时
      leftTimeFun (endT) {
        let end = endT
        let diff = end - Date.parse(new Date()) / 1000
        if (parseInt(diff) < 0) {
          return false
        }
        let hours = parseInt(diff / 60 / 60 % 24)
        let minutes = parseInt(diff / 60 % 60)
        let seconds = parseInt(diff % 60)
        let result = hours + '小时' + minutes + '分' + seconds + '秒'
        if (hours <= 0 && minutes <= 0 && seconds <= 0) {
          return false
        }
        return result
      },
      // 取消原因弹窗关闭之前
      cancelReasonPop (done) {
        this.cancelReason = ''
        done()
      },
      // 立即支付
      immediatePay (orderItem) {
        let amount = orderItem.finalAmount - orderItem.acceptanceAmount
        var limit = false
        if (amount >= 10000) {
          limit = true
        }
        this.$router.push({name: 'Cashier',
          query: {openInvoice: orderItem.hasInvoice, rid: orderItem.orderId, isLimit: limit, totalPrice: amount, payMode: orderItem.payMode, payType: orderItem.payType}})
      },
       // 切换支付状态
      handleTabClick (tab) {
        this.activeName = tab.name
      },
      handleOrderType (status) {
        this.page = 1
        switch (status) {
          case 'all': this.setStatus(-1, -1, -1, ''); break
          case '0': this.setStatus(0, 0, -1); break
          case '1': this.setStatus(1, 0, 0); break
          case '2': this.setStatus(-1, -1, 2); break
          case '3': this.setStatus(-1, 4, -1); break
          case '4': this.setStatus(-1, -1, -1, true); break
        }
        if (this.Exam !== 1) return
        this.fetchOrderMana()
      },
      // 订单类型查询
      setStatus (pay, order, deliver, excep = false) {
        this.payStatus = pay
        this.orderStatus = order
        this.deliverStatus = deliver
        this.exception = excep
      },
      // 查询订单的时间条件
      chooseDate (val) {
        if (!val) {
          this.startTime = ''
          this.endTime = ''
          return
        }
        let startTime = val[0]
        let endTime = val[1]
        this.startTime = formatDate(startTime)
        this.endTime = formatDate(endTime)
      },
      // 获取订单管理列表
      async fetchOrderMana () {
        // let loading = this.$loading({target: '.order_mana_wrapper'})
        let res = await getOrderMana(this.orderStatus, this.startTime, this.endTime, this.hasInvoice, this.page, this.number, this.payStatus, this.deliverStatus, this.searchName, this.exception)
        res = res.data
        if (res.resultCode && res.resultCode === 2000) {
          // loading.close()
          this.orderManaObj = res.data
        } else {
          this.$message({
            message: res.resultMsg,
            type: 'wraming'
          })
        }
      },
      // 分页
      handlePage (page) {
        this.page = page
        this.fetchOrderMana()
      },
      // 显示上传支付凭证
      uploadPayment (paymentId) {
        this.payVoucherVisi = true
        this.paymentId = paymentId
      },
      // 关闭上传支付凭证
      closeVoucherDialog (value) {
        if (value) {
          this.fetchOrderMana()
        }
        this.payVoucherVisi = false
      },
      // 显示取消订单弹窗
      showCancelOrder (id) {
        this.cancelOrderId = id
        this.cancelVisi = true
      },
      // 提交取消订单
      async submitCancelOrder () {
        let res = await cancelOrder(this.cancelOrderId, this.cancelReason)
        if (res.data.resultCode && res.data.resultCode === 2000) {
          this.fetchOrderMana()
          this.cancelVisi = false
          this.cancelReason = ''
        } else {
          this.$message({
            message: '取消订单失败',
            type: 'wraming'
          })
        }
      },
      // 查看物流单号
      async fetchWatchTransport (id) {
        this.translist = []
        this.transObj = {}
        let res = await getTracesInfo(id)
        if (res.data.resultCode && res.data.resultCode === 2000) {
          this.transVisi = true
          let data = res.data.data
          if (data.traces && data.traces.length > 0) {
            this.translist = data.traces.reverse()
          }
          this.transSuccess = data.success
          this.transObj['shipperName'] = data.shipperName
          this.transObj['shipperCode'] = data.shipperCode
          this.transObj['logisticCode'] = data.logisticCode
        } else {
          this.transVisi = false
          this.$message({
            message: '查询物流失败',
            type: 'wraming'
          })
        }
      },
      orderDetailLink (id) {
        this.$router.push({name: 'orderDetail', params: {'orderId': id}})
      },
      // 再来一单
      async fetchAnotherOrder (orderId) {
        this.getMoreMsg = []
        this.getMoreProductIds = []
        let moreGoodsOver = []
        let res = await getAnotherOrder(orderId)
        if (res.data.resultCode && res.data.resultCode === 2000) {
          let data = res.data.data
          data.map((item, index) => {
            if (item.msg && !item.success) {
              this.getMoreMsg.push(item.msg)
            }
            if (item.success) {
              this.getMoreProductIds.push(item.productId)
            }
            if (item.msg && item.success) {
              moreGoodsOver.push(item)
            }
          })
          // 再来一单库存不够
          if (moreGoodsOver.length) {
            this.$store.commit('MOREGOODSOVER', moreGoodsOver)
          }
          // 无法加入购物车
          if (this.getMoreMsg.length) {
            this.showGetMoreMsgVisi = true
          } else {
            this.$router.push({name: 'ShopCart'})
            setSession('getmoreIds', this.getMoreProductIds)
          }
        } else {
          this.$message.error({
            message: res.data.resultMsg
          })
        }
      },
      handleMoreBtn () {
        if (this.getMoreProductIds.length) {
          this.$router.push({name: 'ShopCart'})
          setSession('getmoreIds', this.getMoreProductIds)
        } else {
          this.showGetMoreMsgVisi = false
        }
      },
      hasAnother (order, deliver) {
        return [1, 2].includes(deliver) || [1, 2, 3].includes(order) || this.exception
      }
    },
    beforeRouteLeave (to, from, next) {
      clearInterval(this.timer)
      next()
    },
    mounted () {
      if (this.Exam !== 1) return
      !this.levelInfoObj.purchaserId && this.getUserLevelInfo() // 不存在会员等级 重新请求
      // this.fetchOrderMana()
      this.handleOrderType(this.activeName)
    },
    filters: {
      formatDate,
      webOrderFilter (itemObj) {
        let deliver = itemObj.deliverStatus
        let pay = itemObj.payStatus
        let order = itemObj.orderStatus
        if (deliver === 1 || deliver === 2) {
          return '已发货'
        } else if (order === 2 || order === 3 || order === 1) {
          return '已取消'
        } else if (pay === 0 || pay === 3) {
          return '待支付'
        } else if (pay === 2) {
          return '待审核'
        } else if (deliver === 0) {
          return '待发货'
        } else if (order === 4) {
          return '已结束'
        }
      }
    },
    watch: {
      cancelReason (newval, oldval) {
        if (newval.length >= 100) {
          if (oldval !== 100) {
            this.$message({
              message: '字数最多100个',
              type: 'danger'
            })
          }
          this.cancelReason = this.cancelReason.substring(0, 100)
        }
      },
      activeName (newval) {
        console.log('监测name')
        let status = newval
        this.page = 1
        switch (status) {
          case 'all': this.setStatus(-1, -1, -1, ''); break
          case '0': this.setStatus(0, 0, -1); break
          case '1': this.setStatus(1, 0, 0); break
          case '2': this.setStatus(-1, -1, 2); break
          case '3': this.setStatus(-1, 4, -1); break
          case '4': this.setStatus(-1, -1, -1, true); break
        }
        if (this.Exam !== 1) return
        this.fetchOrderMana()
      }
    }
  }
</script>
<style lang='scss' scoped>
  .date_box{
    margin-top: 30px;
    margin-bottom: 30px;
  }
  .input_style{
    display: inline-block;
    width: 230px;
  }
  .query-falg{
    padding-left: 20px;
  }
  .cancelarea{
    box-sizing: border-box;
    width: 100%;
    outline: none;
    padding: 15px;
    // background: #F9F9F9;
    border: 1px solid #DDDDDD;
    // box-shadow: inset 0 1px 2px 0 rgba(0,0,0,0.17);
    border-radius: 2px;
  }
  .payinfo_box{
    display: block;
    background: #FFFFFF;
    border: 1px solid #DCDCDC;
    border-radius: 2px;
    margin-bottom: 20px;
    cursor: pointer;
    .payinfo_head{
      background: #F8F8F8;
      padding: 20px 23px 23px 42px;
      @include border_bt(#ECECEC);
      .status{
        @include fontbase(#FF7300, 20px, 28px);
        margin-bottom: 4px;
      }
      .status_over{
        color:#666666;
      }
      .detail{
        @include fontbase(#858585, 14px, 30px);
        position: relative;
        letter-spacing: 0.05rem;
        p{
          white-space: nowrap;
          position: absolute;
          top: 30px;
          right: 0;
        }
      }
      .money{
         @include fontbase(#FF7300, 20px);
         font-weight:600;
      }
    }
    .payinfo_content{
      display: table;
      width: 100%;
      height: 122px;
      & > div{
        vertical-align: middle;
        display:table-cell
      }
      .pay_img{
        width: 60px;
        padding: 20px 45px;
        & > img{
          width: 60px;
          height: 60px;
        }
      }
      .order_info{
        padding: 20px 15px;
        @include fontbase(#333333,14px ,25px);
        p {
          line-height: 20px;
        }
        .order_num{
          color: #858585;
          margin-bottom: 9px;
        }
      }
      .order_rt{
        max-height: 79.6px;
        padding: 20px;
        width: 315px;
        line-height: 30px;
        text-align: right;
      }
    }
  }
  .btns_box{text-align: center;}
  .transport_tip{
    position: relative;
    &_inner{
      position: absolute;
      top: 36px;
      right: 0;
      z-index: 55;
      &::before{
        position: absolute;
        top: -14px;
        right: 12%;
        content: '';
        width: 0;
        border: 6px solid transparent;
        border-bottom: 8px solid #ff6000;
      }
    }
    .trans_company{
      border-bottom: 1px solid #e7e4e4;
      margin-bottom: 10px;
      text-align: center;
    }
    &_load{
      color: #ff6000;
    }
    &_box{
      max-height: 250px;
      width: 270px;
      overflow: auto;
      padding: 10px 12px;
      color: #000;
      text-align: left;
      text-decoration: none;
      background-color: #fff;
      border-radius: 4px;
      border: 1px solid #ff6000;
    }
    &_group{
      padding-left: 24px;
      list-style-type: disc;
    }
    &_item{
      margin-bottom: 12px;
      list-style: disc;
      font-size: 12px;
      line-height: 18px;
    }
    &_item_active{
      color: #ff6000;
    }
  }
  .submitBtn{
    float: right;
     // margin-top: 20px;
  }
  .avatar-uploader {
      width: 140px;
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      &:hover{
        border-color: #409EFF;
      }
    }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 140px;
    height: 140px;
    line-height: 140px;
    text-align: center;
  }
  .avatar {
    width: 140px;
    height: 140px;
    display: block;
  }
  .btn-query{
    background: #FFCC00;
    border-radius: 4px;
    font-size: 14px;
    height: 40px;
    margin-left: 20px;
  }
  .btn-order{
    font-size:14px;
    cursor: pointer;
    padding:0 5px;
    line-height: 1.5;
  }
  .btn{
    display: inline-block;
    margin-bottom: 5px;
    width: 140px;
    height:35px;
    line-height: 35px;
    text-align: center;
    border-radius: 4px;
    font-size: 16px;
    cursor: pointer;

  }
  .btn-yellow{
    background: #FFDE00;
    color: #6B6B6B;
  }
</style>

